package wechat

import (
	"errors"
	"reflect"
	"strings"
)

const (
	MATCHTYPE_PREFIX = "PREFIX"
	MATCHTYPE_EQUAL  = "EQUAL"
	MATCHTYPE_REGEXP = "REGEXP"
)

type Helper struct {
	MatchType  string
	MatchValue string
	Operate    interface{}
}

var GHelpers []Helper = []Helper{}

func GetHelperContent(reqObj interface{}, reqText string) (string, error) {
	for _, helper := range GHelpers {
		if (helper.MatchType == MATCHTYPE_PREFIX && strings.HasPrefix(reqText, helper.MatchValue)) ||
			(helper.MatchType == MATCHTYPE_EQUAL && reqText == helper.MatchValue) {
			return DoOperate(reqObj, reqText, helper.Operate)
		}
	}
	//return "", errors.New("NO_MATCH_OPER")
	return "", nil
}

func DoOperate(reqObj interface{}, reqText string, operate interface{}) (string, error) {
	inter_type := reflect.TypeOf(operate).String()

	if inter_type == "string" {
		return operate.(string), nil
	} else if inter_type == "func(interface {}, string) (string, error)" {
		func_ref := operate.(func(interface{}, string) (string, error))
		return func_ref(reqObj, reqText)
	} else {
		return "", errors.New("UN_FUNC:" + inter_type)
	}
}

func Register(m_type, m_value string, operate interface{}) {
	GHelpers = append(GHelpers, Helper{m_type, m_value, operate})
}
